package com.qqserver.service;

import com.qqcommon.Message;
import com.qqcommon.MessageType;
import com.qqcommon.User;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

public class QQServer {
    private ServerSocket serverSocket = null;
    //用户验证
    private boolean checkUser(String userId,String passwd){
        //获取到仓库中的用户
        User user = UserStore.getValidUsers().get(userId);
        if (user==null){
            return false;
        }
        if (!(user.getPasswd().equals(passwd))){
            return false;
        }
        return true;
    }

    public QQServer() {
        System.out.println("服务端在9999端口监听中.....");
        try {
            //端口可以写在配置文件中，方便更改
            serverSocket = new ServerSocket(9999);
            //启动服务端推送消息线程
            new Thread(new SendNewsToAll()).start();

            while (true) {//保持持续监听
                Socket socket = serverSocket.accept();//等待连接请求，无连接请求时会阻塞
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                User u = (User) ois.readObject();
                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

                //定义Message对象用于回复客户端
                Message message = new Message();
                //进行验证
                if (checkUser(u.getUserId(),u.getPasswd())){
                    message.setMesType(MessageType.MESSAGE_LOGIN_SUCCEED);
                    //将Message回复给客户端
                    oos.writeObject(message);
                    //创建一个线程和客户端保持通信，该线程需要持有socket对象
                    ServerConnectClientThread serverConnectClientThread = new ServerConnectClientThread(socket,u.getUserId());
                    //启动通信线程
                    serverConnectClientThread.start();
                    //把该线程放入到一个集合对象中，方便管理
                    ManageServerConnectClientThread.addServerConnectClientThread(u.getUserId(),serverConnectClientThread);

                }
                else {
                    //登陆失败
                    System.out.println("用户"+u.getUserId()+"登陆失败");
                    message.setMesType(MessageType.MESSAGE_LOGIN_FAIL);//返回登陆失败信息
                    oos.writeObject(message);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //服务端退出while循环，说明不在监听，关闭Serversocket
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
